package org.xbl.xchain.sdk.types;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class TxResponse {

    private Integer code;

    private String codeSpace;

    //block 模式下是msg   其他模式为错误日志
    private String log;

    private String data;

    private String hash;

    //block 模式下有height
    private Long height;
    //block 模式下可能会有
    private String proposalId;

    public Boolean isSuccess() {
        return code != null && code == 0;
    }

    public void initForModeBlockResult(String args) {
        JSONObject jsonObject = JSONObject.parseObject(args);
        this.hash = jsonObject.getString("hash");
        this.height = jsonObject.getLongValue("height");

        JSONObject checkTx = jsonObject.getJSONObject("check_tx");
        //checktx error
        if (checkTx.getInteger("code") != 0) {
            this.code = checkTx.getInteger("code");
            this.codeSpace = checkTx.getString("codespace");
            this.log = checkTx.getString("log");
            this.data = checkTx.getString("data");
        } else {
            JSONObject deliverTx = jsonObject.getJSONObject("deliver_tx");
            this.code = deliverTx.getInteger("code");
            this.codeSpace = deliverTx.getString("codespace");
            this.log = deliverTx.getString("log");
            this.data = deliverTx.getString("data");
            // proposalId 从 log中分析
            if(this.code == 0) {
                this.proposalId = parseProposalId(this.log);
            }
        }
    }

    public String parseProposalId(String log) {
        String proposalId = null;
        if(StringUtils.isNotEmpty(log)) {
            JSONObject resMsgJSONObject = JSON.parseArray(log).getJSONObject(0);
            JSONArray eventsJSONArray = resMsgJSONObject.getJSONArray("events");
            for(Object eventObject : eventsJSONArray){
                JSONObject eventJsonObject = JSON.parseObject(JSON.toJSONString(eventObject));

                JSONArray attributesJSONArray = eventJsonObject.getJSONArray("attributes");
                for(Object attributeObject : attributesJSONArray){
                    JSONObject attributeJsonObject = JSON.parseObject(JSON.toJSONString(attributeObject));
                    String akey = attributeJsonObject.getString("key");
                    if("proposalId".equals(akey) || "proposal_id".equals(akey)){
                        proposalId = attributeJsonObject.getString("value");
                        break;
                    }
                }

            }
        }
        return proposalId;
    }

    public String getErrMsg(){
        return this.isSuccess() ? null : log;
    }

}
